// import { EditMode } from './EditMode'
class EntryRefactor {
  static createRefactorElement (sentence, focusEntryEl) {
    let focusId = focusEntryEl ? focusEntryEl.id : null
    let childArr = sentence.childNodes
    let newInnerHtml = ''
    for (let i = 0; i < childArr.length; i++) {
      let id = childArr[i].id
      let focusClass = focusId === id ? 'focus' : ''
      if (childArr[i].nodeType === 3) {
        newInnerHtml += childArr[i].nodeValue.replace(
          /(.)/g,
          '<span class="w-refactor"><span class="w-refactor-content">$1</span></span>'
        )
      } else if (childArr[i].classList[0] === 'entry') {
        let entryInnerHtml = childArr[i].innerHTML
        let wTag = `<span class="w-refactor"><span class="w-refactor-content selected ${focusClass}">$1</span></span>`
        entryInnerHtml = entryInnerHtml.replace(/(.)/g, wTag)
        entryInnerHtml = `<span id="${id}" class="spt start ${focusClass}" draggable="true"><span class="spt-block-container"><span class="spt-block start ${focusClass}">&zwnj;</span></span></span></span>${entryInnerHtml}<span class="spt end ${focusClass}" draggable="true"><span class="spt-block-container"><span class="spt-block end ${focusClass}">&zwnj;</span></span></span>`
        newInnerHtml += entryInnerHtml
      } else {
        newInnerHtml += childArr[i].outerHTML
      }
    }
    let outerHtml = `<div id="container" class="w-refactor-container">${newInnerHtml}</div>`
    let doc = new DOMParser().parseFromString(outerHtml, 'text/html')
    return doc.getElementById('container')
  }

  // 获取前一个包含指定className的元素
  static getPrevElIncludeClass (el, className) {
    while (el && (el = el.previousElementSibling)) {
      if (el.classList.contains(className)) {
        return el
      }
    }
    return null
  }

  // 获取后一个包含指定className的元素
  static getNextElIncludeClass (el, className) {
    while (el && (el = el.nextElementSibling)) {
      if (el.classList.contains(className)) {
        return el
      }
    }
    return null
  }

  static listenersDispenser (sentence) {
    // 可拖拽的范围
    let posStart = 0
    let posEnd = 0
    // 分隔符设置监听器
    let sptArr = sentence.getElementsByClassName('spt')
    for (let i = 0; i < sptArr.length; i++) {
      let el = sptArr[i]
      el.ariaPosInSet = i
      el.ondragstart = event => {
        let sptElPos = parseInt(el.ariaPosInSet)
        let startWordEl = EntryRefactor.getNextElIncludeClass(
          sptArr[sptElPos - 1],
          'w-refactor'
        )
        let endWordEl = EntryRefactor.getPrevElIncludeClass(
          sptArr[sptElPos + 1],
          'w-refactor'
        )
        posStart = startWordEl ? startWordEl.ariaPosInSet : 0
        posEnd = endWordEl ? endWordEl.ariaPosInSet : wArr.length - 1
        // console.log(posStart+"-"+posEnd);
        event.dataTransfer.setData('sptIdx', i)
        event.dataTransfer.setDragImage(new Image(), 0, 0)
        event.dataTransfer.effectAllowed = 'move'
      }
      el.onmouseleave = () => {
        el.firstChild.classList.remove('selected')
      }
      el.onmouseenter = () => {
        el.firstChild.classList.add('selected')
      }
    }
    // 每个字设置监听器
    let wArr = sentence.getElementsByClassName('w-refactor')
    for (let i = 0; i < wArr.length; i++) {
      let el = wArr[i]
      el.ariaPosInSet = i
      // 设置拖拽事件
      el.ondrop = event => {
        let sptIdx = event.dataTransfer.getData('sptIdx')
        let sptEl = sptArr[sptIdx]
        let isStartSptEl = sptEl.classList.contains('start')
        // 修改拖拽元素前先记录其位置
        let fromEl = EntryRefactor.getPrevElIncludeClass(sptEl, 'w-refactor')
        let fromPos = fromEl ? fromEl.ariaPosInSet : -1
        // 判断落点在字的左侧还是右侧
        let offsetX = event.clientX - el.getBoundingClientRect().left
        let elWidthHalf = el.offsetWidth / 2
        if (offsetX < elWidthHalf) {
          // console.log(el.innerHTML + " 左侧");
          if (!isStartSptEl && el.ariaPosInSet === '0') {
            // 结束符不能放到句子前
            el.after(sptEl)
          } else {
            el.before(sptEl)
          }
        } else {
          // console.log(el.innerHTML + " 右侧");
          el.after(sptEl)
        }
        // 修改拖拽元素后记录其位置
        let toEl = EntryRefactor.getPrevElIncludeClass(sptEl, 'w-refactor')
        let toPos = toEl ? toEl.ariaPosInSet : -1
        fromPos = parseInt(fromPos)
        toPos = parseInt(toPos)
        let forward = true
        if (fromPos > toPos) {
          forward = false
          let tmp = toPos
          toPos = fromPos
          fromPos = tmp
        }
        // 重新修改选中区的样式
        let additionClass = sptEl.classList.contains('focus') ? 'focus' : null
        for (let j = fromPos + 1; j <= toPos; j++) {
          let wEl = wArr[j]
          if ((isStartSptEl && forward) || (!isStartSptEl && !forward)) {
            wEl.firstChild.classList.remove('selected', additionClass)
          } else {
            wEl.firstChild.classList.add('selected', additionClass)
          }
        }
      }
      el.ondragover = event => {
        if (
          el.ariaPosInSet < parseInt(posStart) ||
          el.ariaPosInSet > parseInt(posEnd)
        ) {
          // 防止划分词条出现重叠
          return
        }
        // TODO 加上占位元素??
        event.preventDefault()
      }
    }
  }

  static confirmRefactorResult (refactorElement) {
    let sptArr = refactorElement.getElementsByClassName('spt')
    for (let i = 0; i < sptArr.length; i++) {
      let el = sptArr[i]
      if (el.classList.contains('start')) {
        el.replaceChild(
          document.createTextNode('#{' + el.id + '|'),
          el.firstChild
        )
      } else {
        el.replaceChild(document.createTextNode('}'), el.firstChild)
      }
    }
    return refactorElement.textContent.replace(
      /#\{(.+?)\|(.*?)\}/g,
      '<span class="entry" id="$1">$2</span>'
    )
  }
}

export { EntryRefactor }
